package cn.edu.jsu.zjj.service.impl;

import cn.edu.jsu.zjj.constant.CommonConstant;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.context.BaseContext;
import cn.edu.jsu.zjj.exception.AccountNotFoundException;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.PasswordErrorException;
import cn.edu.jsu.zjj.mapper.DocuInduceMapper;
import cn.edu.jsu.zjj.mapper.UserMapper;
import cn.edu.jsu.zjj.model.dto.user.UserLoginRequest;
import cn.edu.jsu.zjj.model.dto.user.UserQueryRequest;
import cn.edu.jsu.zjj.model.entity.DocuInduce;
import cn.edu.jsu.zjj.model.entity.Major;
import cn.edu.jsu.zjj.model.entity.OperLog;
import cn.edu.jsu.zjj.model.entity.User;
import cn.edu.jsu.zjj.model.utils.SqlUtils;
import cn.edu.jsu.zjj.model.vo.UserVO;
import cn.edu.jsu.zjj.service.MajorService;
import cn.edu.jsu.zjj.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MajorService majorService;

    @Autowired
    private DocuInduceMapper docuInduceMapper;

    @Override
    public User login(UserLoginRequest userLoginRequest) {
        String number = userLoginRequest.getNumber();
        String password = userLoginRequest.getPassword();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("number", number);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    @Override
    public User getLoginUser() {
        Long userId = BaseContext.getCurrentId();
        User currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }
        return currentUser;
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BaseException("请求参数为空");
        }
        String number = userQueryRequest.getNumber();
        String name = userQueryRequest.getName();
        String phonenumber = userQueryRequest.getPhoneNumber();
        String email = userQueryRequest.getEmail();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        String sex = userQueryRequest.getSex();
        String address = userQueryRequest.getAddress();
        String degree = userQueryRequest.getDegree();
        String post = userQueryRequest.getPost();
        String nationality = userQueryRequest.getNationality();
        String politicalStatus = userQueryRequest.getPoliticalStatus();
        String teachingSubjects = userQueryRequest.getTeachingSubjects();
        String academicDegree = userQueryRequest.getAcademicDegree();
        String major = userQueryRequest.getMajor();
        String almaMater = userQueryRequest.getAlmaMater();
        String mailAddress = userQueryRequest.getMailAddress();
        String wxNumber = userQueryRequest.getWxNumber();
        String qq = userQueryRequest.getQq();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(number), "number", number);
        queryWrapper.eq(StringUtils.isNotBlank(phonenumber), "phone_number", phonenumber);
        queryWrapper.eq(StringUtils.isNotBlank(nationality), "nationality", nationality);
        queryWrapper.eq(StringUtils.isNotBlank(politicalStatus), "politicalStatus", politicalStatus);
        queryWrapper.eq(StringUtils.isNotBlank(almaMater), "almaMater", almaMater);
        queryWrapper.eq(StringUtils.isNotBlank(mailAddress), "mailAddress", mailAddress);
        queryWrapper.eq(StringUtils.isNotBlank(wxNumber), "wxNumber", wxNumber);
        queryWrapper.eq(StringUtils.isNotBlank(qq), "qq", qq);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(email), "email", email);
        queryWrapper.like(StringUtils.isNotBlank(sex), "sex", sex);
        queryWrapper.like(StringUtils.isNotBlank(address), "address", address);
        queryWrapper.like(StringUtils.isNotBlank(degree), "degree", degree);
        queryWrapper.like(StringUtils.isNotBlank(post), "post", post);
        queryWrapper.like(StringUtils.isNotBlank(teachingSubjects), "teachingSubjects", teachingSubjects);
        queryWrapper.like(StringUtils.isNotBlank(academicDegree), "academicDegree", academicDegree);
        queryWrapper.like(StringUtils.isNotBlank(major), "major", major);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), CommonConstant.SORT_ORDER_ASC.equals(sortOrder), sortField);
        return queryWrapper;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setSelectedMajor(user.getMajor());

        Long majorId = user.getMajorId();
        Major majorRow = majorService.getById(majorId);
        if (majorRow == null) {
            return userVO;
        }
        String[] treePath = majorRow.getTreePath().split("-");
        if (treePath.length == 3) {
            userVO.setCollege(majorService.getById(Integer.parseInt(treePath[0])).getName());
            userVO.setDepartment(majorService.getById(Integer.parseInt(treePath[1])).getName());
            userVO.setCurrentMajor(majorService.getById(Integer.parseInt(treePath[2])).getName());
        }
        return userVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 导出教师数据模板报表
    }

    @Override
    public OperLog setOperLog() {
        User loginUser = this.getLoginUser();
        return OperLog.builder()
                .userId(loginUser.getId())
                .userName(loginUser.getName())
                .operTime(LocalDateTime.now())
                .build();
    }

    @Override
    public List<User> selectList() {
        return userMapper.selectList(null);
    }

    @Override
    public boolean checkUserMajorId(String userMajorId) {
        List<DocuInduce> docuIncludes = docuInduceMapper.selectList(new LambdaQueryWrapper<>());
        for (DocuInduce docuInclude : docuIncludes) {
            List<String> majorIds = Arrays.asList(docuInclude.getMajorId().split("-"));
            if (majorIds.contains(userMajorId)) {
                return true;
            }
        }
        return false;
    }
}